package hotel.meituan.oversea.api.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import hotel.base.oversea.utils.HttpClientBaseAuth;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author HuangT
 * @Date 2020/9/3 14:45
 */
@Configurable
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            String accessToken = HttpClientBaseAuth.getAuthTokenByAppname("fpadmin");
            requestTemplate.header("Authorization", "bearer  " + accessToken);
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                Enumeration<String> values = request.getHeaders(name);
                while (values.hasMoreElements()) {
                    String value = values.nextElement();
                    if (value.contains("xml")) {
                        value = "application/json";
                    }

                    System.out.println(name + "---" + value);
                    requestTemplate.header(name, value);
                }
            }
        }
        if (!requestTemplate.headers().containsKey("authorization")) {
            String accessToken = HttpClientBaseAuth.getAuthTokenByAppname("fpadmin");
            requestTemplate.header("Authorization", "bearer  " + accessToken);
        }
    }

}
